package cn.smbms.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.pojo.Role;
import cn.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.Page;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("/user")
public class UserController {
	private Logger log = Logger.getLogger(getClass());

	@Resource
	private UserService usi;
	@Autowired
	private RoleService rsi;

	@RequestMapping(value = "/login.html")
	public String login() {
		log.debug("UserController welcoem SMBMS==============");
		return "login";
	}

	@RequestMapping(value = "/dologin.html", method = RequestMethod.POST)
	public String doLogin(@RequestParam String userCode,
			@RequestParam String userPassword, HttpSession session,
			HttpServletRequest request) {
		
		log.debug("doLogin================");
		User user = usi.userCode(userCode);
		if (user != null) {
			user = null;
			user = usi.login(userCode, userPassword);
			if (user != null) {
				session.setAttribute(Constants.USER_SESSION, user);
				return "redirect:/user/main.html";
			} else {
				throw new RuntimeException("密码输入错误！");
			}
		} else {
			throw new RuntimeException("用户名不存在！");
		}
	}

	@RequestMapping(value = "/main.html")
	public String main(HttpSession session) {
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "redirect:/user/login.html";
		}
		return "frame";
	}

	/*
	 * @ExceptionHandler(value={RuntimeException.class}) public String
	 * handlerException(RuntimeException e,HttpServletRequest req){
	 * req.setAttribute("error", e.getMessage()); return "login"; }
	 */
	@RequestMapping("list")
	public String userList(
			@RequestParam(value = "queryname", required = false) String queryname,
			@RequestParam(value = "queryUserRole", required = false) String Role,
			@RequestParam(value = "pageIndex", required = false) String Index,
			Model model) {
		Page page = new Page();
		Integer _role = null;
		if (Role != null) {
			if (Role.equals("0")) {
				_role = null;
			} else {
				_role = Integer.parseInt(Role);
			}
		}
		if (Index == null) {
			Index = "1";
		}
		if (queryname == null) {
			queryname = "";
		}
		int _index = (Integer.parseInt(Index) - 1) * 5;

		page.setData(usi.UserList(queryname, _role, _index));
		page.setPageNumber(5);
		page.setTotalCount(usi.getCount(queryname, _role));
		page.setCurPage(Integer.parseInt(Index));

		model.addAttribute("page", page);
		model.addAttribute("roleList", rsi.getRoleList());
		model.addAttribute("queryUserRole", _role);
		model.addAttribute("queryname", queryname);
		return "userlist";
	}

	

	@RequestMapping(value = "useradd.html", method = RequestMethod.GET)
	public String addUser(Model model) {
		model.addAttribute("roleList", rsi.getRoleList());
		return "useradd";
	}

	@RequestMapping("useraddsave.html")
	public String addUserSave(
			User user,
			HttpSession session,
			HttpServletRequest request,
			@RequestParam(value = "a_idPicPath", required = false) MultipartFile attach) {
			String idPicPath=null;
		if (!attach.isEmpty()) {
			//获取路径
			String path = request.getSession().getServletContext().getRealPath
					("statics" + File.separator + "uploadFile");
			//设置文件名
			String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
			//控制大小
			if(attach.getSize()>500000){
				request.setAttribute("uploadFileError", "文件大小不能超过500KB");
				return "useradd";
			}
			
			File targetFile=new File(path,fileName);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			try{
				attach.transferTo(targetFile);
				idPicPath=request.getContextPath() + File.separator + "statics" + 
						 File.separator + "uploadFile" + File.separator + fileName;
			}catch(Exception e){
				e.printStackTrace();
				request.setAttribute("uploadFileError", "上传失败！");
				return "useradd";
			}
		}
		
		user.setIdPicPath(idPicPath);
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION))
				.getId());
		user.setCreationDate(new Date());
		if (usi.useradd(user) > 0) {
			return "redirect:/user/list";
		}
		return "useradd";
	}

	@RequestMapping(value = "usermodify.html", method = RequestMethod.GET)
	public String getUserById(String uid, Model model) {
		User user = usi.getById(uid);
		model.addAttribute(user);
		return "usermodify";
	}

	@RequestMapping(value = "usermodifysave.html", method = RequestMethod.POST)
	public String modifUserysave(User user, HttpSession session) {
		user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION))
				.getId());
		user.setModifyDate(new Date());
		if (usi.userUp(user) > 0) {
			return "redirect:/user/list";
		}
		return "usermodify";
	}

	@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
	public String view(@PathVariable String id, Model model) {
		User user = usi.getById(id);
		model.addAttribute(user);
		return "userview";
	}
	
	@RequestMapping(value="/ucexist")
	@ResponseBody
	public Object userCodeIsExist(String userCode){
		HashMap<String, String> resultMap=new HashMap<String,String>();
		if(StringUtils.isNullOrEmpty(userCode)){
			resultMap.put("userCode", "isNull");
		}else{
			User user=usi.userCode(userCode);
			if(user!=null){
				resultMap.put("userCode", "exist");
			}else{
				resultMap.put("userCode", "noexist");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping(value="/view",method=RequestMethod.GET)
	@ResponseBody
	public Object view(@RequestParam String id){
		User user=null;
		if(id==null||id.equals("")){
			return "nodata";
		}else{
			try{
				user=usi.getById(id);
			}catch(Exception e){
				e.printStackTrace();
				return "failed";
			}
		}
		return user;
	}
	
	@RequestMapping(value="/password.html")
	public String toUpPwd(HttpSession session){
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "redirect:/user/login.html";
		}
		return "pwdmodify";
	}
	
	@RequestMapping(value="/pwdmodify",method=RequestMethod.GET)
	@ResponseBody
	public Object isOldPwd(@RequestParam String oldpassword,HttpSession session){
		HashMap<String, String> resultMap=new HashMap<String,String>();
		if(session.getAttribute(Constants.USER_SESSION) == null){
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldpassword)){
			resultMap.put("result", "error");
		}else if(usi.login(((User)session.getAttribute(Constants.USER_SESSION)).getUserCode(), oldpassword)==null){
			resultMap.put("result", "false");
		}else{
			resultMap.put("result", "true");
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping("/savePwd")
	public String savePwd(String newpassword,HttpSession session){
		String code=((User)session.getAttribute(Constants.USER_SESSION)).getUserCode();
		if(usi.pwdUp(code, newpassword)>0)
			return "redirect:/user/login.html";
		else
			return "pwdmodify";
	}
	
	@RequestMapping(value="/getRoleList")
	@ResponseBody
	public Object getRoleList(){
		List<Role> list=new ArrayList<Role>();
		list=rsi.getRoleList();
		return list;
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Object delUser(String uid){
		HashMap<String, String> resultMap=new HashMap<String,String>();
		if(usi.delById(uid)>0){
			resultMap.put("delResult", "true");
		}else{
			resultMap.put("delResult", "false");
		}
		return resultMap;
	}
}
